<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<button class="btn">插入100000个元素</button>
		<script>
			const btn = document.querySelector('.btn');
			const datas = new Array(100000).fill(0).map((_, i) => i);
			
			btn.onclick = () => {
				performChunk(datas, () => {
					for (const item of datas) {
						const div = document.createElement('div');
						div.textContent = item;
						document.body.appendChild(div);
					}
				}, task => {
					setTimeout(() => {
						task(time => time < 16);
					}, 30);
				});
			};
			
			function performChunk(datas, consumer, chunkSplitor) {
				if (datas.length === 0) {
					return 0;
				}
				let i = 0;
				
				function _run() {
					if (i === datas.length) {
						return;
					}
					chunkSplitor(hasTime => {
						const now = Date.now();
						// 空闲时间是否大于0
						while (hasTime(Date.now() - now) && i< datas.length) {
							// 还有空闲时间
							consumer(datas[i], i);
							i++;
						};
					});
				}
				
				_run();
			}
		</script>
	</body>
</html>